/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.knolle.vistas;

import java.awt.event.ActionEvent;
import java.beans.IntrospectionException;
import java.util.Collection;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import org.marcelo.agro.core.api.InterfaceCampanhas;
import org.marcelo.agro.entidades.*;
import org.marcelo.agro.nodos.CampaniasChildFactory;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.StatusDisplayer;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.nodes.*;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;
import org.openide.util.lookup.Lookups;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.knolle.vistas//VistaCampanhas//EN",
autostore = false)
@TopComponent.Description(preferredID = "VistaCampanhasTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "leftSlidingSide", openAtStartup = true)
@ActionID(category = "Window", id = "org.knolle.vistas.VistaCampanhasTopComponent")
@ActionReference(path = "Menu/Campañas"  , position = 1200 )
@TopComponent.OpenActionRegistration(displayName = "#CTL_VistaCampanhasAction",
preferredID = "VistaCampanhasTopComponent")
@Messages({
    "CTL_VistaCampanhasAction=VistaCampanhas",
    "CTL_VistaCampanhasTopComponent=VistaCampanhas Window",
    "HINT_VistaCampanhasTopComponent=Lista de Todas las Campañas"
})
public final class VistaCampanhasTopComponent extends TopComponent implements ExplorerManager.Provider, LookupListener{

    private static final ExplorerManager em = new ExplorerManager();
    private Boolean VerCampanhasActivas = true;
    private Lookup.Result result = null;
    private Node root;
    InterfaceCampanhas ic = Lookup.getDefault().lookup(InterfaceCampanhas.class);
    
    public VistaCampanhasTopComponent() {
        initComponents();
        associateLookup(ExplorerUtils.createLookup(em, getActionMap()));
        setName(Bundle.CTL_VistaCampanhasTopComponent());
        setToolTipText(Bundle.HINT_VistaCampanhasTopComponent());
       
       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        beanTreeView2 = new org.openide.explorer.view.BeanTreeView();

        jScrollPane1.setViewportView(beanTreeView2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.openide.explorer.view.BeanTreeView beanTreeView2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
        List<Campanas> listCampanas ;
//        Estos datos cargarlos en background
//        Debo utiliar
        if (VerCampanhasActivas)
            listCampanas = ic.getCampanasActivas();
        else
            listCampanas = ic.getCampanasNoActivas();
//        Aca suelo tener problemas al abrir, parece que no esta inicializado, o no retorna valores
//        Ahora probe inicializar valores, vamos a ver que onda
        root = new AbstractNode(Children.create(new CampaniasChildFactory(listCampanas), true) );
        root.setDisplayName("Lista de Campañas");
//        Fin del background
//        Aqui agregar las acciones para invocar al wizard
        em.setRootContext(root);
        result = Utilities.actionsGlobalContext().lookupResult(Campanas.class);
        result.addLookupListener(this);
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
        try {
            //puede lanzar excepciones las ignoramos
            result.removeLookupListener(this);
        }
        catch(Exception ignore){}
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
    
    
    @Override
    public ExplorerManager getExplorerManager() {
       return em;
    }

    @Override
    public void resultChanged(LookupEvent le) {
//        Chequear que la fuente sea el result;
         Lookup.Result r = (Lookup.Result) le.getSource();
         //Falta chequear la fuente, para que no se dispare los eventos de este mismo formulario
         Collection<? extends Campanas> campaniasList = r.allInstances();
         //Chequear que el nodo esta en las opciones
         if (campaniasList != null) {
             for (Campanas campania : campaniasList) {
                 Node node = root.getChildren().findChild(campania.getNombre());
                 if (node == null) {
                    //Crear un nodo para el componente
                    //Node[] agregar = {node};
                    //root.getChildren().add(agregar);
                    //Agregar el nodo
                    StatusDisplayer.getDefault().setStatusText("Agregando nodo",200);     
                 }
                 else { 
                     StatusDisplayer.getDefault().setStatusText("No se Agrego nodo",200);     
                 }
             }
         
         }
         
       
    }
    
    //Fabrica de Nodos para el treeView
    private final class CampanasChildFactory extends ChildFactory<Campanas> {
        private List<Campanas> campanhasList; 
        
        
        public CampanasChildFactory(List<Campanas> list){
           campanhasList = list;
        }
        
        
        /**
         * Crea las claves para el treeView
         * @param list
         * @return 
         */
        
        @Override
        protected boolean createKeys(List<Campanas> list) {
            for (Campanas campanhas : campanhasList) {
                list.add(campanhas);
            }
            return true;
        }

        @Override
        protected Node createNodeForKey(Campanas key) {
//            return super.createNodeForKey(key);
            //Realizar una consulta en la base de datos para este objeto
            //cargar los datos y pasarlos al LotesPorCampanaFactoryNode
//            List<LotesPorCampana> lotesPorCampanaList = ControllerCampañas.getLotesParaCampanha(key);
//            Node result = new AbstractNode(Children.create(new LotesPorCampanaChildFactory(lotesPorCampanaList), true), Lookups.singleton(key));
//            result.setDisplayName(key.getNombre());
            try {
                CampanasBeanNode result = new CampanasBeanNode(key);             
            //Acciones del los Nodos Campanhas
                return result;
            }
            catch (IntrospectionException ie) {
                ie.printStackTrace();
                return null;
            }
        }
        
        
    }         
    private final class LotesPorCampanaChildFactory extends ChildFactory<LotesPorCampana>{
            
            private final List<LotesPorCampana> lotesList;

            public LotesPorCampanaChildFactory(List<LotesPorCampana> list) {
               lotesList = list;
            }
            
            
            
            @Override
            protected boolean createKeys(List<LotesPorCampana> list) {
                for(LotesPorCampana lotePorCampana : lotesList){
                   list.add(lotePorCampana);
                }
                return true;
            }

            @Override
            protected Node createNodeForKey(LotesPorCampana key) {
                try {
                    return  new LotesPorCampanaBeanNode(key);
                }
                catch(IntrospectionException ie) {
                    ie.printStackTrace();
                    return null;
                }
                
            }
            
            
        }
        
        private final class CampanasBeanNode extends AbstractNode {
            private Campanas campana;

            public CampanasBeanNode(Campanas bean) throws IntrospectionException {
                //Aca debo realizar la consulta y traer los datos para los hijos
                super(Children.create(new LotesPorCampanaChildFactory(ic.getLotesParaCampanha(bean)), true), Lookups.singleton(bean)); 
                campana = bean;
            }
            
            @Override
            public String getDisplayName(){
               return campana.getNombre();
            }
            
            @Override
            public String getShortDescription(){
               return campana.getDescripcion();
            }
            
        
        }
        
        private final class LotesPorCampanaBeanNode extends AbstractNode {
            private static final String TOP_COMPONENT = "ActividadesTopComponent";
            private LotesPorCampana lotePorCapama;
            
            public LotesPorCampanaBeanNode(LotesPorCampana bean) throws IntrospectionException {
                super(Children.LEAF, Lookups.singleton(bean));
                lotePorCapama = bean;
            }
            
            @Override
            public String getDisplayName(){
                return lotePorCapama.getLotes().getNombre()+ " : "+ lotePorCapama.getLotes().getCompania();
            }
            
            @Override
            public String getShortDescription(){
                return lotePorCapama.getLotes().getCompania();
            }

            @Override
            public Action[] getActions(boolean context) {
                return new Action[] {new AccionesLotes("Agregar Actividad")};
            }

            @Override
            public String getHtmlDisplayName() {
                
                StringBuilder sb = new StringBuilder();

                sb.append("<html>");

                sb.append("<p style='font-weight: bold'>").append( lotePorCapama.getLotes() ).append("</p>");

                sb.append("<p style='font-size: small'>").append( lotePorCapama.getLotes().getCompania() ).append("</p>");

                sb.append("</html>");

                return sb.toString();
                
            }

            @Override
            public Action getPreferredAction() {
             return  new AbstractAction() {

                @Override
                public void actionPerformed(ActionEvent e) {
                       ActividadesTopComponent atc = (ActividadesTopComponent) WindowManager.getDefault().findTopComponent(TOP_COMPONENT);
                       atc.open();
                       atc.requestActive();
                }
            };
                
            }
            
            
            
            
            
        }
        
        /**
         * Clase para las Acciones de los Nodos Lotes
         */
        private final class AccionesLotes extends AbstractAction{
            PanelAgregarActividades2 atp;
            DialogDescriptor dd;
            public AccionesLotes(){
               putValue(NAME, "Agregar Actividad?");               
            }
            
            public AccionesLotes(String comando){
               putValue(NAME, comando);               
            }
            
            @Override
            public void actionPerformed(ActionEvent e) {
                //Metodo para agregar actividades a un lote dado
                //Al realizar click en uno de los lotes del Arbol se muestra el menu contextual 
                if (e.getSource() == DialogDescriptor.OK_OPTION ){
                       try {
                           if (atp.guardar()){
                               dd.setClosingOptions(null);
                           }
                       }
                       catch (Exception ex){
                           //Voy a pensar que hago en caso de una excepcion
                       }
                }
                else if (e.getSource() == DialogDescriptor.CANCEL_OPTION ) {
                   dd.setClosingOptions(null);
                }
                else{
                //para que el usuario ingrese la actividad
                LotesPorCampana obj = getLookup().lookup(LotesPorCampana.class);
//                PanelAgregarActividades atp=new PanelAgregarActividades(actividad);
                atp = new PanelAgregarActividades2(obj.getCampanas(),obj.getLotes());
                dd = new DialogDescriptor(atp, "Agregar Actividad", false, this); //NOI18N
//                dd.setButtonListener(atp);
                dd.setClosingOptions(
                        new Object[]{DialogDescriptor.CANCEL_OPTION} 
                        );
                DialogDisplayer.getDefault().notifyLater(dd);
//                DialogDisplayer.getDefault().createDialog(dd).setVisible(true);
                //El tema es quien va a encargarse de guardar???
                }
            }
        
        }
        
        private final class AccionesCampanas extends AbstractAction {
              public AccionesCampanas(){
                  putValue(NAME,"Editar Campaña");//NOI18N
              }

            @Override
            public void actionPerformed(ActionEvent e) {
                Campanas obj = getLookup().lookup(Campanas.class);
                System.out.print(e.getActionCommand());
                JOptionPane.showMessageDialog(null,"Editar la Campaña: "+ obj.getNombre());
            }
              
        
        }
        
    
    
    
    
}
